﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Drawing;

namespace com.hyrentals.common.image
{
    public class ImageManagerService
    {
        private const string DEFAULT_IMAGE_FORMAT = ".jpeg";
        private const long DEFAULT_IMAGE_QUALITY = 90L;

        public static void Init()
        {
            ImageDirectoryManager.Init();
        }

        public static string GenerateImageId(ImageSourceEnum src)
        {
            string newId = Guid.NewGuid().ToString("N");
            return newId + ((byte)src).ToString("x2");
        }

        public static void InsertImage(string id, Stream imageStream, string extension)
        {
            string originalImageDir = ImageDirectoryManager.GetOriginalImageDir(id);
            if (!Directory.Exists(originalImageDir))
            {
                Directory.CreateDirectory(originalImageDir);
            }
            Bitmap image = new Bitmap(imageStream, true);
            ImageProcessor.SaveOriginalImage(image, Path.Combine(originalImageDir, id + extension), extension);


            string defaultImageDir = ImageDirectoryManager.GetDefaultImageDir(id);
            if (!Directory.Exists(defaultImageDir))
            {
                Directory.CreateDirectory(defaultImageDir);
            }
            ImageProcessor.SaveImage(image, Path.Combine(defaultImageDir, id + DEFAULT_IMAGE_FORMAT), DEFAULT_IMAGE_FORMAT, DEFAULT_IMAGE_QUALITY);
        }


        public static byte[] GetFillImage(string id, int width, int height)
        {
            return GetImage(id, ImageProcessEnum.Fill, width, height);
        }

        public static byte[] GetCutImage(string id, int width, int height)
        {
            return GetImage(id, ImageProcessEnum.Cut, width, height);
        }

        public static byte[] GetAdaptiveImage(string id, int width, int height)
        {
            return GetImage(id, ImageProcessEnum.Adaptive, width, height);
        }

        private static byte[] GetImage(string id, ImageProcessEnum process, int width, int height)
        {
            byte[] results = null;
            results = ImageDirectoryManager.GetImageFilePath(id, DEFAULT_IMAGE_FORMAT);

            if (process == ImageProcessEnum.Fill)
            {
                results = ImageProcessor.FillForCustom(results, width, height, 5);
            }
            else if (process == ImageProcessEnum.Cut)
            {
                results = ImageProcessor.CutForCustom(results, width, height, 5);
            }
            else if (process == ImageProcessEnum.Adaptive)
            {
                results = ImageProcessor.AdaptForCustom(results, width, height, 5);
            }
            return results;
        }
    }
}
